package samples;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author lizen
 */
public class S01_ThreadLocalMemoryLeak {
    private static final ThreadLocal<byte[]> threadLocal = new ThreadLocal<>();
    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    public static void test() {
        for (int i = 0; i < 15; i++) {
            executor.execute(() -> {
                threadLocal.set(new byte[1024 * 1024]); // 1MB

                // simulate work
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }

                // remove after use, entry is weak reference but value is strong reference
                threadLocal.remove();
            });
        }
        executor.shutdown();
    }
}
